package com.yjb.tenet.boot.system.application.checker;

import cn.hutool.core.util.ObjectUtil;
import com.yjb.tenet.boot.common.constants.GlobalConstants;
import com.yjb.tenet.boot.common.exception.CustomException;
import com.yjb.tenet.boot.common.exception.enums.ErrorCodeEnum;
import com.yjb.tenet.boot.system.application.service.SysDicDataService;
import com.yjb.tenet.boot.system.domain.entity.SysDicData;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 字典项 数据校验
 * @Author 贾栋栋
 * @Date 2023/3/8 14:04
 **/
@Component
public class SysDicDataChecker {

    @Resource
    private SysDicDataService sysDicDataService;

	/**
	 * 数据唯一校验
	 * @param id
	 * @param dicCode
	 * @param dicValue
	 */
    public void checkForExist(Long id, String dicCode, String dicValue, String dicLabel) {

        if (ObjectUtil.isNotNull(id) || ObjectUtil.isEmpty(dicCode)){
            dicCode = sysDicDataService.getById(id).getDicCode();
        }

        List<SysDicData> list = sysDicDataService.lambdaQuery()
                .eq(SysDicData::getDeleted, GlobalConstants.NOT_DELETED)
                .ne(ObjectUtil.isNotNull(id), SysDicData::getId, id)
                .eq(SysDicData::getDicCode, dicCode).list();

        boolean existValue = list.stream().anyMatch(item -> item.getDicValue().equals(dicValue));
        if (existValue){
            throw new CustomException(ErrorCodeEnum.BUSINESS_FAIL.getCode(), "字典值已存在！");
        }

        boolean existLabel = list.stream().anyMatch(item -> item.getDicLabel().equals(dicLabel));
        if (existLabel){
            throw new CustomException(ErrorCodeEnum.BUSINESS_FAIL.getCode(), "字典标签已存在！");
        }

    }
}
